<?php

namespace Admin\Models\read;

class ArticleChannel extends BaseRead
{

    public $id;
    public $articleid;      //文章ID
    public $channelid;      //栏目/连载ID
    public $type;           //1=栏目，2=连载
    public $status;         //1=未删除，2=已删除

    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        parent::initialize();
        $this->setConnectionService(parent::Service);
    }

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return parent::getTableName('article_channel');
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return ArticleChannel[]
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return ArticleChannel
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    /**
     * 根据文章ID，栏目/连载ID，类型创建model并返回结果
     *
     * @param $articleId
     * @param $channelId
     * @param $type
     * @return bool
     *
     * create by ck 20170318
     * modify by ck 20170331    判断已有则直接返回true，否则删除后新建
     */
    public static function createRecord($articleId, $channelId, $type)
    {
        $oldObj = self::findFirst([
            'conditions' => 'status = 1 AND articleid = :articleid: AND channelid = :channelid: AND type = :type:',
            'bind'       => ['articleid' => $articleId, 'channelid' => $channelId, 'type' => $type]
        ]);
        if($oldObj) return true;
        self::find([
            'conditions' => 'status = 1 AND articleid = :articleid: AND type = :type:',
            'bind'       => ['articleid' => $articleId, 'type' => $type]
        ])->delete();
        $obj = new self;
        $obj->articleid = $articleId;
        $obj->channelid = $channelId;
        $obj->type = $type;
        return $obj->save();
    }

    /**
     * 批量插入文章对应栏目/标签
     *
     * @param $articleId
     * @param $channelArr
     * @return bool
     *
     * create by ck 20170228
     */
//    public static function batchCreateRelation($articleId, $channelArr)
//    {
//        if(count($channelArr) < 1) return true;
//        $tableName = self::getSource();
//        $insertSql = "INSERT INTO {$tableName} (articleid,channelid,status) VALUES ";
//        $valueArr = array();
//        foreach($channelArr as $channel){
//            if(!$channel) continue;
//            $valueArr[] = "({$articleId},{$channel},1)";
//        }
//        $insertSql .= implode(',', $valueArr);
//        return \Phalcon\Di::getDefault()->get('readDB')->execute($insertSql);
//    }

}
